package job

import (
	task "Monitor/task"
	"strconv"

	"github.com/astaxie/beego/httplib"
	"github.com/gogf/gf/os/gcfg"
	"github.com/gogf/gf/os/gcron"
)

func MonitorTomcat(req *task.TaskRequest, resp *task.TaskResponse) {
	taskResult := make(map[string]string)
	var status int
	httpclient := httplib.Get(req.RequestCallParams.CommString)
	rsp, err := httpclient.Response()
	if err != nil {
		req.Reply.TaskErr(err)
	}
	if rsp != nil {
		status = rsp.StatusCode
	}
	taskResult["parking_client_alive_http_code"] = strconv.Itoa(status)
	JobLogger.Info("%s %v", req.RequestCallParams.CommString, taskResult)
	req.Reply.TaskDone(taskResult)
}

func HttpRun() {
	apis := gcfg.Instance().GetJsons("client_api")
	for i := 0; i < len(apis); i++ {
		cronString := apis[i].GetString("cron")
		http_url := apis[i].GetString("url")
		http_name := apis[i].GetString("name")
		c := NewCron(cronString, nil, http_name)
		err := c.AddCron()
		if err != nil {
			JobLogger.Error("cron entry err [%s]", err)
			return
		}
		c.SetReplyTask()
		c.SetTaskParams(http_url)
		c.SetCallTask(MonitorTomcat)
		gcron.Start(c.Name)
	}
}

//上报客户端IP地址
func SendClientAddrRun() {
	sendCfg := gcfg.Instance().GetJson("send_client_ip")
	cronString := sendCfg.GetString("cron")
	url := sendCfg.GetString("url")
	name := sendCfg.GetString("name")
	gcron.Add(cronString, func() {
		httpclient := httplib.Get(url)
		rsp, err := httpclient.Response()
		if err != nil {
			JobLogger.Error("rsp send client ip err [%s]", err)
		}
		JobLogger.Debug("request=%s status=%d", url, rsp.StatusCode)
	}, name)
	gcron.Start(name)
}
